using System;
using System.Windows.Forms;
using Jbe.TestSuite.Infrastructure.Interface;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.Commands;
using Jbe.TestSuite.TestDevice.Manager.Services;
using Jbe.TestSuite.TestDevice.Manager.Interface.Services;
using Jbe.TestSuite.TestDevice.Manager.Interface.Constants;
using Jbe.TestSuite.TestDevice.Manager.Views;
using Microsoft.Practices.CompositeUI.SmartParts;
using Jbe.TestSuite.TestDevice.Manager.Properties;
using Jbe.TestSuite.Infrastructure.Interface.Services;
using SCSFContrib.CompositeUI.WinForms.SmartPartInfos;

namespace Jbe.TestSuite.TestDevice.Manager
{
    public class ModuleController : WorkItemController
    {
        private IUIElementCreationService uiElementCreationService;
        private DockPanelSmartPartInfo smartPartInfo;
        private TestDevicesView view;

        [ServiceDependency]
        public IUIElementCreationService UIElementCreationService
        {
            set { uiElementCreationService = value; }
        }

        public override void Run()
        {
            WorkItem.Services.AddNew<TestDeviceManager, ITestDeviceManager>();

            IMenuItem menuItem = uiElementCreationService.CreateMenuItem(
                "Test Devices", Resources.DeviceManager.ToBitmap());
            WorkItem.UIExtensionSites[UIExtensionSiteNames.ViewMenuItem].Add(menuItem);
            menuItem.Click += new EventHandler(TestDevicesMenuItemClick);

            // Do not close the smart part because it is a registered UIExtension site.
            smartPartInfo = new DockPanelSmartPartInfo("Test Devices", "Test Devices");
            smartPartInfo.Icon = Resources.DeviceManager;
            smartPartInfo.DockingType = DockingType.TaskView;
            smartPartInfo.ShowStrategy = new DockStateShowStrategy(DockState.DockLeft);
            view = WorkItem.SmartParts.AddNew<TestDevicesView>();
            WorkItem.Workspaces[WorkspaceNames.DockPanelWorkspace].SmartPartClosing += SmartPartClosing;

            ShowTestDevicesView();
        }

        private void ShowTestDevicesView()
        {
            WorkItem.Workspaces[WorkspaceNames.DockPanelWorkspace].Show(view, smartPartInfo);                        
        }

        #region Command and Event handler

        private void TestDevicesMenuItemClick(object sender, EventArgs e)
        {
            ShowTestDevicesView();
        }

        private void SmartPartClosing(object sender, WorkspaceCancelEventArgs e)
        {
            if (e.SmartPart == view)
            {
                // Do not close the window, only hide it.
                WorkItem.Workspaces[WorkspaceNames.DockPanelWorkspace].Hide(view);
                e.Cancel = true;
            }
        }

        #endregion
    }
}
